var config = require("../../config");
var app = getApp();

Page({
  data: {
    selected: 0,
    specification: true
  },
  onLoad(e) {
    
    let totalPrices = parseInt(e.totalPrices), phoneColor = e.phoneColor, orders = JSON.parse(e.data);
    let ordersId = '';
    for (var i = 0; i < orders.length; i++){
      ordersId += orders[i].id+','
    }
    this.setData({
      ordersId,
      phoneColor,  //手机的颜色
      totalPrices,   //总价
      phoneModelId: e.phoneModelId
    });

  },
  onShareAppMessage() {

  },
  onShow(e) {
    if (e) {
      this.setData({
        obj: e,
        Baddress:e.type == 1 ? true : false
      });
    }
  },

  /**选择手机颜色**/
  color(e) {
    let _this = this, item = e.currentTarget.dataset.index;
    this.setData({
      ColorItem: item
    });

  },

  /**选择维修方式 **/
  RepairMethod(e) {
    let type = e.currentTarget.dataset.index;    
    this.setData({
      selected: e.currentTarget.dataset.index,
      type,
      Baddress:false,
      obj:""
    });

   if(type == 0){
    //  app.aldstat.sendEvent('到店维修', {});
     wx.reportAnalytics('ms_type_shop', {
       'nums': 1
     });
   }else if(type == 1){
    //  app.aldstat.sendEvent('邮寄维修', {});
     wx.reportAnalytics('ms_type_mail', {
       'nums': 1
     });
   }
  },

  ContactWay(e){
    let phone_number = e.detail.value;
    if (phone_number.length > 0 && testPhoneNumber(phone_number) != true){
      this.setData({
        NPfault: {     //未选择手机故障摸版数据
          hint_NPfault: "hint-NPfault",
          info: "手机号格式不正确",
          buttonEvent: "NPfaultButton"
        }
      });
    }
  },
  
  ContactWay2(e) {
    let phone_number = e.detail.value;
    if (phone_number.length > 0 && testPhoneNumber(phone_number) != true) {
      this.setData({
        NPfault: {     //未选择手机故障摸版数据
          hint_NPfault: "hint-NPfault",
          info: "手机号格式不正确",
          buttonEvent: "NPfaultButton"
        }
      });
    }
  },

  /**提交数据**/
  formSubmit(e) {
    var formObj = e.detail.value, checkbox = formObj.checkbox.length ? true : false;
    if (this.data.selected == 0) {
      if (formObj.appellation && formObj.ContactWay && formObj.shop != "" && checkbox == true) {
        if (testPhoneNumber(formObj.ContactWay) == true) {
          PlaceAnOrder1(this, formObj);         
        } else {
          this.setData({
            NPfault: {     //未选择手机故障摸版数据
              hint_NPfault: "hint-NPfault",
              info: "手机号格式不正确",
              buttonEvent: "NPfaultButton"
            }
          });
        }

      } else if (formObj.appellation == "") {
        this.setData({
          NPfault: {     //未选择手机故障摸版数据
            hint_NPfault: "hint-NPfault",
            info: "请填入您的称呼",
            buttonEvent: "NPfaultButton"
          }
        });
      } else if (formObj.ContactWay == "") {
        this.setData({
          NPfault: {     //未选择手机故障摸版数据
            hint_NPfault: "hint-NPfault",
            info: "请填入您的联系方式",
            buttonEvent: "NPfaultButton"
          }
        });
      } else if (formObj.shop == "") {
        this.setData({
          NPfault: {     //未选择手机故障摸版数据
            hint_NPfault: "hint-NPfault",
            info: "请选择门店",
            buttonEvent: "NPfaultButton"
          }
        });
      } else if (checkbox == "") {
        this.setData({
          NPfault: {     //未选择手机故障摸版数据
            hint_NPfault: "hint-NPfault",
            info: "还未同意用户服务协议",
            buttonEvent: "NPfaultButton"
          }
        });
      }
    } else if (this.data.selected == 1) {
      // app.aldstat.sendEvent('邮寄维修下单', {}); 
         
      if (this.data.Baddress && checkbox == true) {
        PlaceAnOrder2(this, formObj.remark);
      } else if (!this.data.Baddress){
        this.setData({
          NPfault: {     //未选择手机故障摸版数据
            hint_NPfault: "hint-NPfault",
            info: "请填入您的回寄地址",
            buttonEvent: "NPfaultButton"
          }
        });

      } else if (checkbox == ""){
        this.setData({
          NPfault: {     //未选择手机故障摸版数据
            hint_NPfault: "hint-NPfault",
            info: "还未同意用户服务协议",
            buttonEvent: "NPfaultButton"
          },
          show_textarea: "show-textarea"          
        });
      }

    }
  },

  /**确定、退出（未选择手机故障摸）**/
  NPfaultButton() {
    this.setData({
      NPfault: {
        hint_NPfault: ""
      },
      shwo_textarea:true
    });
  },

  /**说明**/
  specification() {
    this.setData({
      specification: !this.data.specification
    });
    wx.navigateTo({
      url: '../specification/specification',
      success: function (res) { },
      fail: function (res) { },
      complete: function (res) { },
    })
  },
  selectedShop(){
    app.aldstat.sendEvent('选择门店', {});    
  },
  SelectShop(){
    wx.reportAnalytics('select-shop', {
      'nums': 1
    });
  }
});

/**下单（到店）**/
function PlaceAnOrder1(e,formData) {
  // console.log("yes");
  wx.request({
    method: 'POST',
    url: config.service.PlaceAnOrder,
    data: {
      uid: wx.getStorageSync("loginInfo").uid,
      logintoken: wx.getStorageSync("loginInfo").token,
      is_send:2,
      error_id: e.data.ordersId,
      color: e.data.phoneColor,
      store_id:e.data.obj.id,
      user_nickname: formData.appellation,
      user_mobile: formData.ContactWay,
      category_id:e.data.phoneModelId,
      comment: formData.remark == "" ? '' : formData.remark
    },
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success(res) {
      console.log("下单（到店）:", res);
      if (res.data.code == 1) {
        wx.reportAnalytics('immediately_maintan', {
          'type': '到店维修',
          'nums': 1
        });
        res.data.data.type = 2;
        wx.navigateTo({
          url: '../CheckoutSuccess/CheckoutSuccess?OrderInfo='+ JSON.stringify(res.data.data),
          success: function (res) { },
          fail: function (res) { },
          complete: function (res) { },
        });
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: "loading",
          duration: 2000,
          mask: true
        });
      }
    }
  });
}

/**下单（邮寄）**/
function PlaceAnOrder2(e, remark) {
  // obj.type = 1;
  wx.request({
    method: 'POST',
    url: config.service.PlaceAnOrder,
    data: {
      uid: wx.getStorageSync("loginInfo").uid,
      logintoken: wx.getStorageSync("loginInfo").token,
      is_send: 1,
      back_addr:e.data.obj.id,
      error_id: e.data.ordersId,
      color: e.data.phoneColor,
      category_id: e.data.phoneModelId,
      comment: remark == "" ? '' :remark
    },
    header: {
      'content-type': 'application/x-www-form-urlencoded'
    },
    success(res) {
      console.log(res);
      if (res.data.code == 1) {
        wx.reportAnalytics('immediately_maintan', {
          'type': '邮寄维修',
          'nums': 1
        });       
        res.data.data.type = 1;
        wx.navigateTo({
          url: '../CheckoutSuccess/CheckoutSuccess?OrderInfo='+JSON.stringify(res.data.data),
          success: function (res) { },
          fail: function (res) { },
          complete: function (res) { },
        });
      } else {
        wx.showToast({
          title: res.data.msg,
          icon: "loading",
          duration: 2000,
          mask: true
        });
      }
    }
  });

}

function testPhoneNumber(value) {
  if (/^\d{11}$/.test(value)) {
    return true
  }
}